package mips.instructions;

import mips.Main;

/**
 * TODO fix execute(...) and emit(...)
 * 
 * <code>JR</code> instruction<br/>
 * Jump Register<br/>
 * @author jnmartin84@gmail.com
 */
public class JR extends Instruction {

	private static final JR INSTANCE = new JR();
	private static final String INSTRUCTION_NAME = "JR";

	private JR(){}

	public static final JR getInstance() {
		return INSTANCE;
	}

	/**
	 * <b>Format:</b><br/>
	 * JR rs<br/><br/>
	 * <b>Description:</b><br/>
	 * The program unconditionally jumps to the address contained in general<br/>
	 * register rs, with a delay of one instruction.<br/><br/>
	 * Since instructions must be word-aligned, a <b>Jump Register</b> instruction<br/>
	 * must specify a target register (rs) whose two low-order bits are zero. If<br/>
	 * these low-order bits are not zero, an address exception will occur when the<br/>
	 * jump target instruction is subsequently fetched.<br/><br/>
	 * <b>Operation:</b><br/>
	 * T: temp &larr; GPR[rs]<br/>
	 * PC &larr; temp
	 */
	@Override
	public final void execute(final int instruction) throws mips.exceptions.AddressErrorException {

		final int rs = (instruction >> 21) & 0x0000001F;

		if ((mips.R4300i.GPR[rs] & 0x00000003) == 0) {

			mips.R4300i.PC = mips.R4300i.nPC;
			// double-check this works right!
			mips.R4300i.nPC = (int)(mips.R4300i.GPR[rs] & 0x00000000FFFFFFFFL);
			
			if(Main.tracing) {
				mips.R4300i.targets.put(mips.R4300i.nPC,null);
			}
		} 
		// this isn't implemented right, this shouldn't get thrown until the instruction fetch
		// this means we need to add a flag for the interpreting loop :o
		else {
			throw new mips.exceptions.AddressErrorException(mips.R4300i.PC,instruction);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String emit(final int instruction) {
		
		final int rs = (instruction >> 21) & 0x0000001F;

		return 	"		if ((mips.CPU.GPR["+rs+"] & 0x00000003) == 0) {\n" + 
				"			\n" + 
				"			mips.CPU.PC = mips.CPU.nPC;\n" + 
				"			// double-check this works right!\n" +
				"			mips.CPU.nPC = (int)(mips.CPU.GPR["+rs+"] & 0x00000000FFFFFFFFL);\n" + 
				"		} \n" + 
				"		else {\n" + 
				"			throw new mips.exceptions.AddressErrorException(mips.CPU.PC,"+String.format("0x%08X",instruction)+");\n" + 
				"		}\n";
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName(final int instruction) {
		return getName();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName() {
		return INSTRUCTION_NAME;
	}
}